package com.zj.web.controller;

import com.zj.service.UserService;
import com.zj.web.bean.MyUserDTO;
import com.zj.web.bean.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.security.Principal;
import java.util.List;
import java.util.Optional;

/**
 * 用户管理 REST API控制器
 */
@RestController
@RequestMapping("/user")
public class MyUserController {
    @Autowired
    private UserService userService;

    /**
     * 查询所有用户信息(仅限管理员)
     * 权限：只有拥有‘ADMIN’角色的用户才能访问该接口
     */
    @GetMapping("/getAllUser/{userStatus}")
    @PreAuthorize("hasRole('ADMIN')")  //只有拥有‘ADMIN’角色的用户才能访问该接口
    public ResponseEntity<ResponseResult<List<MyUserDTO>>> getAllUser(@PathVariable("userStatus") Integer userStatus) {
        List<MyUserDTO> lists=userService.getAllUser(userStatus);
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata(lists));
    }

    /**
     * 根据用户id查询用户信息
     * 权限：只有拥有‘ADMIN’角色的用户 或者  该用户自己 才能访问该接口
     */
    @GetMapping("/{userId}")
    public ResponseEntity<ResponseResult<MyUserDTO>> getUserById(@PathVariable("userId") Long userId) {
        //获取当前认证用户的id(从Gateway 传递的 X-User-Id)
        String currentUserId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断当前用户是否是要查询的用户 或者  是否是管理员
        //如果不是管理员，且请求的ID不是当前用户的id，则拒绝访问
        if(!SecurityContextHolder.getContext().getAuthentication().getAuthorities()
                .stream().anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"))&& !currentUserId.equals(userId.toString())){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error("没有权限访问"));
        }

        Optional<MyUserDTO> myUserDTOOptional = userService.getUserById(userId);
        if(myUserDTOOptional.isEmpty()){
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ResponseResult.error("用户不存在"));
        }
        MyUserDTO myUserDTO = myUserDTOOptional.get();
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata(myUserDTO));
    }

    /**
     * 根据用户id更新用户状态
     */
    @PutMapping("/updateUserStatus/{userId}/{userStatus}")
    @PreAuthorize("hasRole('ADMIN')")  //只有拥有‘ADMIN’角色的用户才能访问该接口
    public ResponseEntity<ResponseResult<MyUserDTO>> updateUserStatus(@PathVariable("userId") Long userId,
                                                                      @PathVariable("userStatus") Integer userStatus) {
        MyUserDTO myUserDTO = userService.updateUserStatus(userId, userStatus);
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata(myUserDTO));
    }
    /**
     * 根据用户id更新用户信息
     * //权限： 该用户自己 才能访问该接口
     */
    @PutMapping("/updateUserInfo/{userId}")
    public ResponseEntity<ResponseResult<MyUserDTO>> updateUserInfo(@PathVariable("userId") Long userId,
                                                                    @RequestParam("userName") String userName,
                                                                    @RequestParam("phone") String phone,
                                                                    @RequestParam("email") String email,
                                                                    @RequestPart("avatarImgFile") MultipartFile avatarImgFile,
                                                                    @RequestParam(value = "gender", required = false, defaultValue = "0") int gender) {
        //获取当前认证用户的id(从Gateway 传递的 X-User-Id)
        String currentUserId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断当前用户是否是要查询的用户
        //如果请求的ID不是当前用户的id，则拒绝访问
        if(!currentUserId.equals(userId.toString())){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error("没有权限更新当前id的用户信息"));
        }
        MyUserDTO myUserDTO = new MyUserDTO(userId, userName, phone, email, avatarImgFile, gender);
        MyUserDTO myUserDTO1 = userService.updateUserInfo(userId, myUserDTO);
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata(myUserDTO1));
    }
}
